package org.bjf.security.satoken;

import cn.dev33.satoken.stp.StpInterface;
import com.google.common.collect.Lists;
import org.bjf.modules.sys.bean.SysRole;
import org.bjf.modules.sys.bean.SysRolePerm;
import org.bjf.modules.sys.service.SysRolePermService;
import org.bjf.modules.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class SaPermissionImpl implements StpInterface {

    @Autowired
    private SysRolePermService rolePermService;
    @Autowired
    private SysRoleService roleService;

    /**
     * 查询登录用户有权访问的资源列表
     *
     * @param loginId   登录用户id
     * @param loginType 登录类型
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        if (!SaTokenAdminUtil.TYPE.equals(loginType)) {
            return Collections.emptyList();
        }
        List<SysRolePerm> userPerms = rolePermService.listUserPerm(Long.parseLong(loginId.toString()));
        Map<String, List<SysRolePerm>> moduleGroup = userPerms.stream().collect(Collectors.groupingBy(SysRolePerm::getAuthModuleCode));
        List<String> perms = Lists.newArrayList();
        moduleGroup.forEach((moduleCode, list) -> {
            for (SysRolePerm rolePerm : list) {
                perms.add(rolePerm.getAuthModuleCode() + "-" + rolePerm.getPermMethodCode());
            }
        });

        return perms;
    }

    /**
     * 查询登录用户角色列表
     *
     * @param loginId   登录用户id
     * @param loginType 登录类型
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        if (!SaTokenAdminUtil.TYPE.equals(loginType)) {
            return Collections.emptyList();
        }
        List<SysRole> sysRoles = roleService.listByUser(Long.parseLong(loginId.toString()));
        return sysRoles.stream().map(SysRole::getCode).collect(Collectors.toList());
    }
}
